package com.charm.restaurant.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.charm.restaurant.common.Result;
import com.charm.restaurant.entity.Feedback;
import com.charm.restaurant.service.FeedbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 评价反馈控制器
 */
@Slf4j
@RestController
@RequestMapping("/feedback")
public class FeedbackController {

    @Autowired
    private FeedbackService feedbackService;

    /**
     * 用户提交评价
     */
    @PostMapping
    public Result<Feedback> submit(@RequestBody Feedback feedback) {
        log.info("用户提交评价：{}", feedback);
        return feedbackService.submitFeedback(feedback);
    }

    /**
     * 用户查询自己的评价
     */
    @GetMapping("/user")
    public Result<Page<Feedback>> userFeedbacks(int page, int pageSize, @RequestHeader(value = "X-User-Id", required = false) String userIdHeader) {
        Long userId = 1L; // 默认用户ID

        // 如果请求头中有用户ID，则使用请求头中的用户ID
        if (userIdHeader != null && !userIdHeader.isEmpty()) {
            try {
                userId = Long.parseLong(userIdHeader);
            } catch (NumberFormatException e) {
                log.warn("无效的用户ID格式: {}", userIdHeader);
            }
        }

        log.info("用户查询自己的评价，userId={}, page={}, pageSize={}", userId, page, pageSize);
        return feedbackService.getUserFeedbacks(userId, page, pageSize);
    }

    /**
     * 商家查询评价
     */
    @GetMapping("/merchant")
    public Result<Page<Feedback>> merchantFeedbacks(int page, int pageSize) {
        log.info("商家查询评价，page={}, pageSize={}", page, pageSize);
        return feedbackService.getMerchantFeedbacks(page, pageSize);
    }

    /**
     * 商家回复评价
     */
    @PutMapping("/reply/{id}")
    public Result<Feedback> reply(@PathVariable Long id, @RequestBody Map<String, String> replyMap) {
        log.info("商家回复评价，id={}, reply={}", id, replyMap.get("reply"));
        return feedbackService.replyFeedback(id, replyMap.get("reply"));
    }

    /**
     * 根据ID查询评价详情
     */
    @GetMapping("/{id}")
    public Result<Feedback> getById(@PathVariable Long id) {
        log.info("查询评价详情，id={}", id);
        return feedbackService.getFeedbackById(id);
    }

    /**
     * 删除评价
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        log.info("删除评价，id={}", id);
        return feedbackService.deleteFeedback(id);
    }
}
